<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="condition">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="departments" @row-dblclick="getEmpById" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;"  >
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120">
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100">
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <!-- scope可以获取整行数据 -->
          <span v-if="scope.row.state === 1" style="color: limegreen">启用</span>
          <span v-else-if="scope.row.state === 0" style="color: red">禁用</span>
          <span v-else style="color:gray">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="manager.username" label="负责人" width="120">
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" min-width="180">


      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" v-perm="'department:delete'" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    抽屉-->
    <el-drawer
        title="员工列表!"
        :visible.sync="table"
        direction="rtl"
        size="50%">
      <el-table :data="gridData">
        <el-table-column prop="username" label="姓名" width="120" sortable>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="100"  sortable>
          <template scope="scope">
            <span style="color: #11b95c" v-if="scope.row.state ===1">启用</span>
            <span style="color: red" v-else-if="scope.row.state ===0">禁用</span>
            <span style="color: slategray" v-else>未知</span>
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="100" sortable>
        </el-table-column>

        <el-table-column prop="email" label="邮箱" width="120" sortable>
        </el-table-column>

        <el-table-column prop="age" label="年龄" width="120" sortable>
        </el-table-column>
      </el-table>
    </el-drawer>


    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="pageSize"
                     :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="editForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="负责人">
          <!--
           v-for="item in emps" ： 遍历 emps 也就是我们钩子函数中查询的员工数据
           :label ：我们选中后 在下拉框中展示的值
           :value：是选中后 传到后端的值
           下面的 left和right：下拉出来展示的数据.如果没有他俩 那么会展示 :label的值
           新增的时候：
              它会根据选中的username对应的id 放到 我们v-model 绑定的字段中
           编辑回显：
              它会根据 v-model绑定的值 去找 emps里面 id 和 managerid 相同的username 回显到页面上
              所以首先 我们要保证 emps里面有值 ： 我们在钩子函数获取emps的时候
              保证 editForm.managerId 不能为空 ： 这个数据是列表的当前行的数据，所以在查询列表的时候就需要将managerId查询出来
           -->
          <!--          <el-input type="textarea" v-model="editForm.managerId"></el-input>-->
          <el-select v-model="editForm.managerId" placeholder="请选择">
            <el-option
                v-for="item in emps"
                :label="item.username"
                :value="item.id">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <!--          <el-input type="textarea" v-model="editForm.parentId"></el-input>-->
          <!--          <span class="demonstration">单选选择任意一级选项</span>-->
          <el-cascader
              v-model="editForm.parentId"
              :options="options"
              :props="{ checkStrictly: true,
                value:'id',
                label:'name'
                // children:
              }"
              clearable></el-cascader>


        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>


  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {
  getDepartmentListPage,
  removeDepartment,
  batchRemoveDepartment,
  editDepartment,
  addDepartment
} from '../../api/api';

export default {
  data() {
    return {
      table: false,
      gridData: [],
      emps: [],
      options: [],
      filters: {
        keyword: ''
      },
      currentPage: 1,
      pageSize: 5,
      departments: [],
      total: 0,
      page: 1,
      listLoading: false,
      sels: [],//列表选中列

      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        sn: [
          {required: true, message: '请输入编号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
      },
      //编辑界面数据
      editForm: {
        id: null,
        sn: '',
        name: '',
        state: 0,
        managerId: null,
        parentId: null
      },
    }
  },
  methods: {
    getEmpById(row){
      this.table= true;
      console.log(row.id);
      let para = row.id
      this.$http.get("/emp/getEmployees/" + para)
          .then(result => {
            this.gridData = result.data
          })
    },
    getTree(){
      this.$http.get("/dept/tree")
          .then(result => {
            this.options = result.data
          })
    },
    getEpms() {
      this.$http.get("/emp")
          .then(result => {
            this.emps = result.data
          })
    },
    condition() {
      this.currentPage = 1;
      this.getDepartments();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartments();
    },
    //获取部门列表
    getDepartments() {
      let para = {
        // 配置分页页码
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      // 列表忙等
      this.listLoading = true;
      // 请求后端接口 获取数据
      this.$http.post("/dept", para)
          .then(result => {
            this.listLoading = false;
            // 回调函数
            this.total = result.data.totals;
            this.departments = result.data.rows;
          })
          .catch(result => {
            this.$message({
              message: '提交失败',
              type: 'error',
            });
          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        this.$http.delete("/dept/" + row.id)
            .then(result => {
              this.listLoading = false;

              if (result.data.success) {
                this.$message({
                  message: result.data.msg,
                  type: 'success',
                });
                this.currentPage = 1;
                this.getDepartments();
              } else {
                this.$message({
                  message: result.data.msg,
                  type: 'error',
                });
              }
            })
            .catch(result => {
              this.$message({
                message: '提交失败',
                type: 'error',
              });
            })
      })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";
      this.editFormVisible = true;
      this.editForm = Object.assign({}, row);
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.editFormVisible = true;
      this.editForm = {
        id: null,
        sn: '',
        name: '',
        state: 0,
        managerId: null,
        parentId: null
      };
    },
    //编辑
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.editForm);
            // 因为是取最近一级 所以 当parentId存在时 且 parentId为数组时 才进行长度-1 获取下标
            // 如果不是数组 那么代表当前就是顶级 直接取本身parentId即可
            if (para.parentId && para.parentId instanceof Array) {
              para.parentId = para.parentId[para.parentId.length - 1];
            }
            this.$http.put("/dept", para)
                .then(result => {
                  this.editLoading = false;
                  this.editFormVisible = false;

                  if (result.data.success) {
                    this.$message({
                      message: result.data.msg,
                      type: 'success',
                    });
                    this.getDepartments();
                  } else {
                    this.$message({
                      message: result.data.msg,
                      type: 'error',
                    });
                  }
                })
                .catch(result => {
                  this.$message({
                    message: '删除失败',
                    type: 'error',
                  });
                })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      // sels选中行的数据
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        // let para = {ids: ids};
        this.$http.patch("/dept", ids)
            .then(result => {
              this.listLoading = false;

              if (result.data.success) {
                this.$message({
                  message: result.data.msg,
                  type: 'success',
                });
                this.currentPage = 1;
                this.getDepartments();
              } else {
                this.$message({
                  message: result.data.msg,
                  type: 'error',
                });
              }
            })
      }).catch(() => {
        this.$message({
          message: '删除失败',
          type: 'error',
        });
      });
    }
  },
  mounted() {
    this.getDepartments();
    this.getEpms();
    this.getTree();
  }
}

</script>

<style scoped>

</style>